<template>
  <div class="content-management">
    <h2 class="header">内容管理</h2>

    <!-- 分类 Tabs -->
    <div class="tabs">
      <button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: activeTab === index }"
        @click="activeTab = index"
      >
        {{ tab }}
      </button>
    </div>

    <!-- 内容列表 -->
    <div class="content-list">
      <div
        class="content-item"
        v-for="(item, index) in contentItems"
        :key="index"
        @click="goToDetail(item)"
      >
        <img class="content-img" :src="item.cover" alt="封面图" />
        <div class="content-info">
          <div class="content-title">{{ item.title }}</div>
          <div class="content-meta">
            <span class="type">{{
              typeMap[item.targetType] || '未知类型'
            }}</span>
            <span class="date">{{ formatDate(item.createTime) }}</span>
            <span class="status">状态：{{ statusMap[item.status] }}</span>
          </div>
          <div class="content-footer">
            <div class="content-stats">
              <span>点赞 {{ item.likeCount }}</span>
              <span>评论 {{ item.commentCount }}</span>
            </div>
            <div class="content-actions">
              <button class="edit-btn" @click.stop="editItem(item)">
                编辑
              </button>
              <button class="delete-btn" @click.stop="confirmDelete(item)">
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
      <div class="no-more" v-if="contentItems.length === 0">暂无更多内容</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { getCreateContent } from '@/apis/user' // 按你的路径引入
import { useAccountStore } from '@/stores/useAccountStore.js'
import { useRouter } from 'vue-router'
import { deleteDynamic } from '@/apis/dynamic'
import { deleteArticle } from '@/apis/article'

const uid = useAccountStore().uid // 假设是用户 ID，后续可动态获取
const tabs = ['全部', '动态', '文章']
const activeTab = ref(0)

const allItems = ref([])
const contentItems = ref([])

const typeMap = {
  1: '动态',
  2: '文章',
}

const statusMap = {
  0: '审核中',
  1: '正常',
  2: '封禁中',
}

// 初始化获取内容数据
onMounted(async () => {
  try {
    const res = await getCreateContent(uid)
    allItems.value = res.data || []
    filterByTab()
  } catch (error) {
    console.error('获取内容失败:', error)
  }
})

// 监听 Tab 切换筛选数据
watch(activeTab, filterByTab)

function filterByTab() {
  if (activeTab.value === 0) {
    contentItems.value = allItems.value
  } else {
    contentItems.value = allItems.value.filter(
      (item) => item.targetType === activeTab.value
    )
  }
}

// 日期格式化函数
function formatDate(dateStr) {
  const d = new Date(dateStr)
  return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
}

const router = useRouter()

function goToDetail(item) {
  if (item.targetType === 1) {
    router.push(`/home/dynamic/${item.targetId}`)
  } else if (item.targetType === 2) {
    router.push(`/home/article/${item.targetId}`)
  } else {
    console.warn('未知内容类型', item)
  }
}

function editItem(item) {
  if (item.targetType === 1) {
    router.push(`/creator/image-text-editor/${item.targetId}`)
  } else if (item.targetType === 2) {
    router.push(`/creator/article-editor/${item.targetId}`)
  }
}

// 删除确认函数
const confirmDelete = (item) => {
  // 使用 ElMessageBox 弹出确认框
  ElMessageBox.confirm('确认删除该内容吗？', '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      handleDelete(item) // 用户点击确认，执行删除操作
    })
    .catch(() => {
      ElMessage.info('删除已取消') // 用户点击取消
    })
}

// 删除操作函数
const handleDelete = async (item) => {
  try {
    if (item.targetType === 1) {
      // 动态
      await deleteDynamic(item.targetId)
      ElMessage.success('动态删除成功')
    } else if (item.targetType === 2) {
      // 文章
      await deleteArticle(item.targetId)
      ElMessage.success('文章删除成功')
    } else {
      ElMessage.warning('未知类型无法删除')
      return
    }
    // 删除成功后从列表中移除
    contentItems.value = contentItems.value.filter(
      (contentItem) => contentItem.targetId !== item.targetId
    )
  } catch (error) {
    console.error('删除失败', error)
    ElMessage.error('删除失败')
  }
}
</script>

<style scoped>
.content-management {
  padding: 16px;
  font-family: sans-serif;
}

.header {
  font-size: 20px;
  margin-bottom: 8px;
}

.tabs {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.tabs button {
  background: none;
  border: none;
  padding: 8px 16px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  font-weight: 500;
}

.tabs button.active {
  border-bottom: 2px solid #007bff;
  color: #007bff;
}

.content-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.content-item {
  display: flex;
  border: 1px solid #eee;
  padding: 12px;
  border-radius: 8px;
  gap: 12px;
}

.content-img {
  width: 100px;
  height: 70px;
  object-fit: cover;
  border-radius: 4px;
}

.content-info {
  flex: 1;
}

.content-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 6px;
}

.content-meta {
  font-size: 13px;
  color: #888;
  margin-bottom: 6px;
}

.content-meta span {
  margin-right: 12px;
}

.content-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}

.content-stats span {
  margin-right: 16px;
}

.content-actions button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  margin-left: 12px;
  font-size: 13px;
  color: #007bff;
}

.content-actions .delete-btn {
  color: #dc3545;
}

.no-more {
  text-align: center;
  color: #aaa;
  margin-top: 20px;
}
</style>
